package com.steam.splace;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import thread.DoThreadGet;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import bo.DirectionsJSONParser;
import bo.IsConnected;
import bo.UserFunctions;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.internal.cp;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.gson.Gson;

import dao.DataAccess;
import entity.Category;
import entity.Message;
import entity.Place;
import entity.Region;
import entity.User;

public class SearchActivity extends FragmentActivity implements
		LocationListener {
	private final int category_tag = 4;
	ArrayAdapter<String> adapter;
	Spinner spCategory;
	Spinner spRegion;
	GoogleMap googleMap;
	int positionOnSpin = -1;
	ArrayList<String> dataCat;
	ArrayList<LatLng> markerPoints;
	private final int getfavorite_tag = 9;
	HashMap<String, String> plids;
	float zoomlevel=12;
	private final int searchplace_tag = 8;
	private final int place_tag = 10;
	Location location ;
	Intent pIntent;
	private static int tag = -1;
	Activity currentActivity;
	int uid=-1;
	Button bt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_activity);
		currentActivity=this;
		bt = (Button) this.findViewById(R.id.btOpenAddPlaceActivity);
		uid=getUID();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);		    
		spRegion = (Spinner) this.findViewById(R.id.spRegion);
		spCategory = (Spinner) findViewById(R.id.spCategory);
		fillCategory();
		Gson gson = new Gson();
		ArrayList<Region> regions = new ArrayList<Region>();
		int regionSize = prefs.getInt("regionsize", 0);
		for (int i = 0; i < regionSize; i++) {
			String json = prefs.getString("region_" + i, "");
			regions.add(gson.fromJson(json, Region.class));
		}
		loadRegion(regions);
		if (uid == -1) {
			bt.setVisibility(View.GONE);
		}

		
		
		markerPoints = new ArrayList<LatLng>();

		// Showing status
		// Google Play Services are available

		// Getting reference to the SupportMapFragment of activity_main.xml
		SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);

		// Getting GoogleMap object from the fragment
		googleMap = fm.getMap();

		//CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
		//		new LatLng(21.076591538593824, 105.79306125640869), zoomlevel);
		//googleMap.animateCamera(cameraUpdate);
		// Enabling MyLocation Layer of Google Map
		googleMap.setMyLocationEnabled(true);
		pIntent = new Intent(this, ViewPlaceActivity.class);
		googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {

				marker.showInfoWindow();
				
				return true;
			}
		});
		googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {          
            public void onInfoWindowClick(Marker marker) 
            {
            	pIntent.putExtra("pid",
						Integer.parseInt(plids.get(marker.getId())));
				Log.d("place id", Integer.parseInt(plids.get(marker.getId()))
						+ "");
				startActivity(pIntent);
            }
            });
		LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria cr = new Criteria();
        String provider = locationmanager.getBestProvider(cr, true);
        location = locationmanager.getLastKnownLocation(provider);
      if (location != null) {
				 onLocationChanged(location);
				 locationmanager.requestLocationUpdates(provider, 20000, 0, this);
				 location = locationmanager.getLastKnownLocation(provider);
            double lat=location.getLatitude();
        double lng=location.getLongitude();
        CameraUpdate cameraUpdate1 = CameraUpdateFactory.newLatLngZoom(
				new LatLng(lat, lng), zoomlevel);
		googleMap.animateCamera(cameraUpdate1);
		Log.v("my location",lat+"/"+lng);
        }
	}
	
	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btOpenAddPlaceActivity) {
			Intent addPlaceIntent = new Intent(this, AddPlaceActivity.class);
			startActivity(addPlaceIntent);
		} else if (id == R.id.btFind) {
			googleMap.clear();
			DoThreadGet sp = new DoThreadGet(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			EditText SearchValue = (EditText) findViewById(R.id.txtSearchValue);
			params.add(new BasicNameValuePair("placename",SearchValue.getText().toString()));
			params.add(new BasicNameValuePair("categoryid",((Category) (spCategory.getSelectedItem())).getCategoryid()+""));
			params.add(new BasicNameValuePair("regionid",((Region) (spRegion.getSelectedItem())).getId()+""));
			//System.out.println("search catID:"+((Category) (spCategory.getSelectedItem())).getCategoryid());
			ArrayList l = new ArrayList();
			plids=new HashMap<String, String>();
			l.add(searchplace_tag);
			l.add(params);
			l.add(googleMap);
			l.add(plids);
			sp.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,l);
		}
	}

	private void fillCategory() {
		ArrayList<Category>cat=new ArrayList<Category>();
		Category tmp=new Category(0, "Danh mục", "Danh mục", 0);
		cat.add(tmp);
		  Gson gson = new Gson();
		  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		    int catSize = prefs.getInt("categorysize", 0);		    
		    for(int i=0;i<catSize;i++){
		    	String json = prefs.getString("category_"+i, "");
		    	cat.add(gson.fromJson(json, Category.class));
		    }
		if(cat!=null){
			ArrayAdapter<Category> adapter=new ArrayAdapter<Category>
			 (this,
			 android.R.layout.simple_spinner_item,
			 cat
			 );
			adapter.setDropDownViewResource
			 (android.R.layout.simple_list_item_single_choice);
			Spinner spCategory=(Spinner)this.findViewById(R.id.spCategory);
			spCategory.setAdapter(adapter);
		}
		spCategory.setOnItemSelectedListener(new MyEvent());
	}
	public void loadRegion(ArrayList<Region> regions) {
		if (regions != null) {

			Region regtmp=new Region(0, "Khu vực");
			regions.add(0,regtmp);
			ArrayAdapter<Region> adapter = new ArrayAdapter<Region>(this,
					android.R.layout.simple_spinner_item, regions);
			adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
			
			spRegion.setAdapter(adapter);
		}
	}
	private class MyEvent implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			positionOnSpin = arg2;
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	private String getDirectionsUrl(LatLng origin, LatLng dest) {

		// Origin of route
		String str_origin = "origin=" + origin.latitude + ","
				+ origin.longitude;

		// Destination of route
		String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

		// Sensor enabled
		String sensor = "sensor=false";

		// Building the parameters to the web service
		String parameters = str_origin + "&" + str_dest + "&" + sensor;

		// Output format
		String output = "json";

		// Building the url to the web service
		String url = "https://maps.googleapis.com/maps/api/directions/"
				+ output + "?" + parameters;

		return url;
	}

	private String downloadUrl(String strUrl) throws IOException {
		String data = "";
		InputStream iStream = null;
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL(strUrl);

			// Creating an http connection to communicate with url
			urlConnection = (HttpURLConnection) url.openConnection();

			// Connecting to url
			urlConnection.connect();

			// Reading data from url
			iStream = urlConnection.getInputStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					iStream));

			StringBuffer sb = new StringBuffer();

			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}

			data = sb.toString();
			Toast.makeText(getApplicationContext(), "data:" + data,
					Toast.LENGTH_LONG).show();
			br.close();

		} catch (Exception e) {
			Log.d("Exception while downloading url", e.toString());
		} finally {
			iStream.close();
			urlConnection.disconnect();
		}
		return data;
	}

	private class DownloadTask extends AsyncTask<String, Void, String> {

		// Downloading data in non-ui thread
		@Override
		protected String doInBackground(String... url) {

			// For storing data from web service
			String data = "";

			try {
				// Fetching the data from web service
				data = downloadUrl(url[0]);

			} catch (Exception e) {
				Log.d("Background Task", e.toString());
			}
			return data;
		}

		// Executes in UI thread, after the execution of
		// doInBackground()
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			ParserTask parserTask = new ParserTask();
			Toast.makeText(getApplicationContext(), "result:" + result,
					Toast.LENGTH_LONG).show();
			// Invokes the thread for parsing the JSON data
			parserTask.execute(result);
		}
	}

	private class ParserTask extends
			AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

		// Parsing the data in non-ui thread
		protected List<List<HashMap<String, String>>> doInBackground(
				String... jsonData) {

			JSONObject jObject;
			List<List<HashMap<String, String>>> routes = null;

			try {
				jObject = new JSONObject(jsonData[0]);

				DirectionsJSONParser parser = new DirectionsJSONParser();

				// Starts parsing data
				routes = parser.parse(jObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return routes;
		}

		protected void onPostExecute(List<List<HashMap<String, String>>> result) {
			ArrayList<LatLng> points = null;
			PolylineOptions lineOptions = null;
			MarkerOptions markerOptions = new MarkerOptions();

			// Traversing through all the routes
			for (int i = 0; i < result.size(); i++) {
				points = new ArrayList<LatLng>();
				lineOptions = new PolylineOptions();

				// Fetching i-th route
				List<HashMap<String, String>> path = result.get(i);

				// Fetching all the points in i-th route
				for (int j = 0; j < path.size(); j++) {
					HashMap<String, String> point = path.get(j);

					double lat = Double.parseDouble(point.get("lat"));
					double lng = Double.parseDouble(point.get("lng"));
					LatLng position = new LatLng(lat, lng);

					points.add(position);
				}

				// Adding all the points in the route to LineOptions
				lineOptions.addAll(points);
				lineOptions.width(2);
				lineOptions.color(Color.RED);
			}

			// Drawing polyline in the Google Map for the i-th route
			googleMap.addPolyline(lineOptions);
		}
	}

	@Override
	public void onLocationChanged(Location location) {

		// Getting latitude of the current location
		double latitude = location.getLatitude();

		// Getting longitude of the current location
		double longitude = location.getLongitude();

		// Creating a LatLng object for the current location
		LatLng latLng = new LatLng(latitude, longitude);

		// Showing the current location in Google Map
		//googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

		// Zoom in the Google Map
		//googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

	}
public int getUID(){
	
	DoThreadGet thread1 = new DoThreadGet(this);
	ArrayList params1 = new ArrayList();
	params1.add(getfavorite_tag);
	DataAccess da = new DataAccess(this);
	int uid = -1;
	try {
		da.open();
		if (da.getUserInUse() != null)
			uid = da.getUserInUse().getId();
		else
			uid = -1;

	} catch (SQLException e) {
		// TODO Auto-generated catch block
		// e.printStackTrace();
		uid = -1;
	} finally {
		da.close();
	}
	return uid;
}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);		
		if(uid!=-1){
			getMenuInflater().inflate(R.menu.main, menu);
		}
		else getMenuInflater().inflate(R.menu.menunologin, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (item.getItemId() == R.id.menuSearch) {
			if (!this.getClass().getSimpleName().equals("SearchActivity")) {

				Intent searchIntent = new Intent(this, SearchActivity.class);
				startActivity(searchIntent);
			}
		} else if (item.getItemId() == R.id.menuProfile) {
			if (!this.getClass().getSimpleName().equals("ProfileActivity")) {
				Intent profileIntent = new Intent(this, ProfileActivity.class);
				startActivity(profileIntent);
			}
		}
		else if(item.getItemId() == R.id.SignOut){
			DataAccess da=new DataAccess(this);
			try {
				da.open();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			da.signOut();
			da.close();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			Editor prefsEditor = prefs.edit(); 
			prefsEditor.putInt("uid", -1);
			prefsEditor.putString("token", "");
				prefsEditor.commit();
			this.finish();
			Intent loginIntent = new Intent(this, MainActivity.class);
			startActivity(loginIntent);
		}
		else if(item.getItemId() == R.id.menuSignUp){
			if (!this.getClass().getSimpleName().equals("SignUpActivity")) {

				Intent signUpActivity = new Intent(this, SignUpActivity.class);
				startActivity(signUpActivity);
			}
		}
		else if(item.getItemId() == R.id.menuForgot){
			if (!this.getClass().getSimpleName().equals("ForgotPasswordActivity")) {
				Intent forgotPasswordActivity = new Intent(this, ForgotPasswordActivity.class);
				startActivity(forgotPasswordActivity);
			}
		}
		else if(item.getItemId() == R.id.menuAddPlace){
			if (!this.getClass().getSimpleName().equals("AddPlaceActivity")) {
				Intent addPlaceActivity = new Intent(this, AddPlaceActivity.class);
				startActivity(addPlaceActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSignIn){
			if (!this.getClass().getSimpleName().equals("MainActivity")) {
				Intent mainActivity = new Intent(this, MainActivity.class);
				startActivity(mainActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSearchArea){
			if (!this.getClass().getSimpleName().equals("SearchByAreaActivity")) {
				Intent searchAreaActivity = new Intent(this, SearchByAreaActivity.class);
				startActivity(searchAreaActivity);
			}
		}
		else if(item.getItemId() == R.id.menuFavorite){
			if (!this.getClass().getSimpleName().equals("FavoriteActivity")) {

				Intent favoriteActivity = new Intent(this, FavoriteActivity.class);
				startActivity(favoriteActivity);
			}
		}
		
		return true;
	}
}
